import json
import logging

from django.http import JsonResponse
from django.http import QueryDict
from django.shortcuts import render

# Create your views here.
from django.views import View
from xingzheng.extension import EntryEmployeesSQL
from xingzheng.extension import AssetAllocaSQL
from xingzheng.extension import UpdateEntrySQL
from xingzheng.extension import AllAssetAllocaSQL
from xingzheng.extension import UpdateAAssetSQL
from xingzheng.extension import RetAssetSQL

from database.connection import Link_database

from xingzheng.take_data import asset_alloca
from xingzheng.take_data import sel_entry
from xingzheng.take_data import all_asset_alloca
from xingzheng.take_data import asset_name
from xingzheng.take_data import asset_serial
from xingzheng.take_data import asset_user


import datetime
import copy



logger = logging.getLogger(__name__)


class AttendanceData(View):
    """ 考勤数据处理 """

    def heavy(self, a):
        # 去重
        b = []
        for i in a:
            c = '-'.join(i)
            b.append(c)

        d = copy.deepcopy(b)

        for i_1 in b:
            num = 0
            for i_2 in d:
                if i_1[:-7] == i_2[:-7]:
                    num += 1
                if num > 1:
                    d.remove(i_2)
                    num -= 1

        k = []
        for j in d:
            k.append(j[:-9])

        clock = []
        for u in k:
            if k.count(u) < 2:
                clock.append(u.split('-')[1])

        data = []
        for c in d:
            y = c.split('-')
            data.append(y[1][:-1])

        return {"data": data, "clock": clock}

    def dateRanges(self, beginDate, endDate):
        dates = []
        dt = datetime.datetime.strptime(beginDate, '%Y-%m-%d')
        date = beginDate[:]
        while date <= endDate:
            dates.append(date)
            dt = dt + datetime.timedelta(1)
            date = dt.strftime('%Y-%m-%d')
        return dates

    def loadDatadet(self, txt, serial):

        """ 传入一个用户考勤编号，返回所考勤数据 """

        dataset = []
        for line in self.txt_data:
            temp1 = line.decode('gbk').strip('\n')
            temp2 = temp1.split('\t')
            dataset.append(temp2)

        # a = self.dateRanges(beginDate, endDate)
        a = self.dateRanges(dataset[0][-1].split()[0].replace('/', '-'),
                            dataset[-1][-1].split()[0].replace('/', '-'))  # 生成传入txt所有日期

        user_list = []
        date_list = []
        xx = serial.split('/')

        for i in dataset:
            if i[2] in xx:
                date_list.append((i[6].split(' ')[0]).replace('/', '-'))
                user_list.append([i[2], i[6]])

        b = list(set(date_list))
        no_punch_date = (list(set(a).difference(set(b))))
        data = self.heavy(user_list)  # 去重的打卡记录数据
        return {"no_punch_date": no_punch_date, "punch_card_record": data['data'],
                "lack_punch_card": data['clock']}  # no_punch_date无打卡记录，punch_card_record所有打卡记录,lack_punch_card缺少打卡记录

    def post(self, request):
        txt = request.FILES.get('txt')
        # beginDate = request.POST.get('beginDate')
        # endDate = request.POST.get('endDate')
        self.txt_data = txt.readlines()

        # 获取所有考勤编号
        DB, Cursor = Link_database()
        account_sql = """ select serial,name from user where state != '%s' """ %('已离职')
        Cursor.execute(account_sql)
        user_list = Cursor.fetchall()
        data = []
        for user in user_list:
            userdata = self.loadDatadet(txt, user[0])
            data.append({"user_serial": user[0], "username": user[1], "serial_data": userdata})

        return JsonResponse({"code": 200, "result": 'OK', "data": data})


class EntryView(View):
    """员工录入视图"""

    def get(self, request):
        id = request.GET.get('user_id')

        try:
            id = int(id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': 'user_id错误', 'data': []})

        try:
            # 查询
            query = sel_entry(id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', 'data': []})

        data = {"user_id": query[0], "name": query[1], "gender": query[3], "born_date": query[4], "height": query[5],
                "weight": query[6], "ethnic": query[7], "political": query[8], "marriage": query[9],
                "id_card": query[10],
                "phone": query[11], "emergency_phone": query[12], "hk_address": query[13], "jt_address": query[14],
                "xz_address": query[15], "learn": query[16], "professional": query[17], "graduation_date": query[18],
                "school": query[19], "members": query[20], "jobs": query[21], "department": query[31],
                "induction_date": query[24], "positive_date": query[25],
                "departure_date": query[26], "bank_name": query[27], "bank": query[28], "state": query[29],
                "serial": query[30]}

        return JsonResponse({"code": 200, 'result': 'OK', 'data': data})

    def post(self, request):
        # 参数
        data = request.POST.get('data')  # json字符串
        try:
            data = json.loads(data)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', 'data': []})
        try:
            a = EntryEmployeesSQL(data)
            if not a:
                return JsonResponse({"code": 400, 'result': '录入失败', 'data': []})
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '存储错误', 'data': []})

        return JsonResponse({"code": 200, 'result': '录入成功', 'data': []})


class UpdateEntryView(View):
    """员工信息修改"""

    def post(self, request):
        data = request.POST.get('data')

        try:
            data = json.loads(data)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', 'data': []})

        try:
            # 修改
            q = UpdateEntrySQL(data)
            if not q:
                return JsonResponse({"code": 400, 'result': 'json中缺少参数', 'data': []})
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '修改错误', 'data': []})

        return JsonResponse({"code": 200, 'result': 'OK', 'data': []})


class AllAssetAllocaView(View):
    """总资产"""
    def get(self, request):
        page = request.GET.get('page')
        try:
           page = (int(page) - 1) * 20
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', 'data': []})

        try:
            # 查询
            sum, query = all_asset_alloca(page)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', 'data': []})
        # print(query)
        try:
            # 数据
            sum_data = []  # 总数
            for i in sum:
                a = {
                    "name": i[0],
                    "stock": i[1],
                    "is_using": i[1] - i[2],
                    "kucun": i[2],
                    "sunhuai": i[1] - i[3]
                }
                sum_data.append(a)

            details = []  # 详情
            for u in query:
                m = {
                    "serial": u[0],
                    "assets_name": u[1],
                    "department": u[6],
                    "user_name": u[3],
                    "state": u[4],
                    "note": u[5]
                }
                details.append(m)
            data = {"sum_data": sum_data, "details": details}
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '数据错误', 'data': []})

        return JsonResponse({"code": 200, 'result': 'OK', 'data': data})

    def post(self, request):
        name = request.POST.get('name')
        number = request.POST.get('number')

        try:
            number = int(number)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', 'data': []})

        try:
            # 生成数据
            AllAssetAllocaSQL(name, number)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '存储错误', 'data': []})

        return JsonResponse({"code": 200, 'result': 'OK', 'data': []})


class AssetAllocaView(View):
    """资产分配"""

    def get(self, request):
        user_id = request.GET.get('user')

        try:
            user_id = int(user_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', 'data': []})

        try:
            # 查询
            query = asset_alloca(user_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', 'data': []})

        try:
            # 数据处理
            data = []
            for i in query:
                a = {
                    "serial": i[0],
                    "name": i[1],
                    "department": i[6],
                    "user_name": i[3],
                    "state": i[4],
                    "note": i[5]
                }
                data.append(a)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '数据错误', 'data': []})

        return JsonResponse({"code": 200, 'result': 'OK', 'data': data})

    def post(self, request):
        serial = request.POST.get('serial')
        user_id = request.POST.get('user')
        # department = request.POST.get('department')

        try:
            serial = int(serial)
            user_id = int(user_id)
            # department = int(department)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', 'data': []})

        asset_obj = AssetAllocaSQL(serial, user_id)

        try:
            # 存储
            asset_obj.update()
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '存储失败', 'data': []})

        return JsonResponse({"code": 200, 'result': '录入成功', 'data': []})


class UpdateAAssetView(View):
    """修改个人资产"""

    def post(self, request):
        serial = request.POST.get('serial')
        # department = request.POST.get('department')
        # user_id = request.POST.get('user')
        state = request.POST.get('state')
        note = request.POST.get('note')

        try:
            serial = int(serial)
            # department = int(department)
            # user_id = int(user_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', 'data': []})

        try:
            # 修改
            UpdateAAssetSQL(serial, state, note)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '修改错误', 'data': []})

        return JsonResponse({"code": 200, 'result': 'OK', 'data': []})


class RetAssetView(View):
    """归还资产"""
    def post(self, request):
        serial = request.POST.get('serial')

        try:
            serial = int(serial)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', 'data': []})

        try:
            RetAssetSQL(serial)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '归还错误', 'data': []})

        return JsonResponse({"code": 200, 'result': 'OK', 'data': []})


class AssetNameView(View):
    """资产名下拉框"""
    def get(self, request):
        try:
            # 查询
            query = asset_name()
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', 'data': []})

        try:
            # 数据
            data = []
            for i in query:
                data.append(i[0])
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '数据错误', 'data': []})

        return JsonResponse({"code": 200, 'result': 'OK', 'data': data})


class AssetSerialView(View):
    """资产名编号下拉框"""
    def get(self, request):
        asset_name = request.GET.get('name')
        try:
            # 查询
            query = asset_serial(asset_name)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', 'data': []})

        try:
            # 数据
            data = []
            for i in query:
                data.append(i[0])
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '数据错误', 'data': []})

        return JsonResponse({"code": 200, 'result': 'OK', 'data': data})


class AssetUserView(View):
    """部门下员工拉框"""
    def get(self, request):
        department = request.GET.get('department')

        try:
            department = int(department)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', 'data': []})

        try:
            # 查询
            query = asset_user(department)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', 'data': []})

        try:
            # 数据
            data = []
            for i in query:
                a = {
                    "id": i[0],
                    "name": i[1]
                }
                data.append(a)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '数据错误', 'data': []})

        return JsonResponse({"code": 200, 'result': 'OK', 'data': data})


class UpdateResume(View):
    """ 更新用户简历 """

    def post(self, request):
        user_id = request.POST.get('user_id')
